﻿using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

/*
 * User: Ert
 * Date: 6/25/2012
 * Time: 8:04 PM
 */

namespace ahbst
{
	public class Database
	{
		public static Hashtable products = new Hashtable();
		public static Hashtable inventory = new Hashtable();
		
		public static void AddProduct(int id, Product product)
		{
			products[id] = product;
		}
		
		public static Product GetProduct(int id)
		{
			return products[id] as Product;
		}
		
		public static void AddInventory(int id, Inventory inv)
		{
			inventory[id] = inv;
		}
		
		public static Inventory GetInventory(int id)
		{
			return inventory[id] as Inventory;
		}
		
		public static void Save()
		{
			SaveFile("products.dat", products);
			SaveFile("inventory.dat", inventory);
		}
		
		public static void Load()
		{
			products = LoadFile("products.dat");
			inventory = LoadFile("inventory.dat");
		}
		private static void SaveFile(string fileName, Hashtable table)
		{
			using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
			{
				try 
				{
					BinaryFormatter bf = new BinaryFormatter();
					bf.Serialize(fs, table);
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
			}
		}
		
		private static Hashtable LoadFile(string fileName)
		{
			Hashtable table = null;
			using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
			{
				try 
				{
					BinaryFormatter bf = new BinaryFormatter();
					table = bf.Deserialize(fs) as Hashtable;
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
				return table;
			}
		}
	}
}